<template>
  <div class="system-user-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="system-user-search mb15">
        <el-form ref="searchFormRef" :model="searchForm" inline>
          <el-form-item label="活动名称" prop="name">
            <el-input v-model="searchForm.name" placeholder="请输入"> </el-input>
          </el-form-item>
          <!-- <el-form-item label="活动类型" prop="type">
            <CommonSelect
              v-model="searchForm.type"
              placeholder="请输入"
              :options="dictsStore.ActivityTypes"
              label-key="text"
            >
            </CommonSelect>
          </el-form-item> -->
          <!-- <el-form-item label="商户名称" prop="merchant_name">
            <el-input v-model="searchForm.merchant_name" placeholder="请输入"> </el-input>
          </el-form-item> -->
          <!-- <el-form-item label="活动状态" prop="status">
            <CommentSelect v-model="searchForm.status" :options="ActivityStatusOptions" placeholder="请选择" />
          </el-form-item> -->
          <el-form-item>
            <el-button size="default" type="primary" @click="refresh">
              <el-icon>
                <ele-Search />
              </el-icon>
              查询
            </el-button>
            <el-button size="default" @click="onRest">
              <el-icon>
                <ele-RefreshRight />
              </el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
        <div class="table-tool-bar">
          <el-button
            size="default"
            type="primary"
            v-if="$can(ButtonPermission.CREATE_ACTIVITY)"
            @click="handleAdd()"
          >
            <el-icon>
              <ele-Plus />
            </el-icon>
            新增活动
          </el-button>
        </div>
      </div>
      <el-table :data="tableData.list" v-loading="loading" row-key="id" border style="width: 100%">
        <el-table-column prop="name" label="活动名称" width="140" fixed="left"></el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <ActivityStatusComp :status="row.status" :deadline="row.deadline" />
          </template>
        </el-table-column>
        <el-table-column
          prop="summary"
          label="活动简介"
          width="140"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="开始时间" width="160">
          <template #default="scope">
            <span>{{ formatDate(scope.row.start_date, 'time') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="end_date" label="结束时间" width="160">
          <template #default="scope">
            <span>{{ formatDate(scope.row.end_date, 'time') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="deadline" label="报名截止时间" width="160">
          <template #default="scope">
            <span>{{ formatDate(scope.row.deadline, 'time') }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="contact_name" label="联系人姓名" width="100" show-overflow-tooltip>
        </el-table-column> -->
        <el-table-column prop="contact_phone" label="客服电话" width="130" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="attention" label="注意事项" width="130" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="area_names" label="活动地区" width="130">
        </el-table-column>
        <el-table-column prop="address" label="详细地址" width="130">
        </el-table-column>
        <el-table-column prop="merchant.name" label="商户" width="120" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="160" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDate(scope.row.created_at, 'time') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
              v-if="$can(ButtonPermission.READ_ACTIVITY)"
              size="small"
              text
              type="primary"
              @click="handleManageItems(scope.row)"
            >
              管理项目
            </el-button>
            <el-button
              v-if="$can(ButtonPermission.UPDATE_ACTIVITY)"
              size="small"
              text
              type="primary"
              @click="handleUploadPhoto(scope.row)"
            >
              管理照片
            </el-button>
            <el-button
              v-if="$can(ButtonPermission.UPDATE_ACTIVITY)"
              size="small"
              text
              type="primary"
              @click="handleDistributionSettings(scope.row)"
            >
              分销设置
            </el-button>
            <el-dropdown @command="(command: string) => onCommand(command, scope.row)">
              <el-button size="small" text type="primary" style="margin-left: 12px">操作</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="$can(ButtonPermission.READ_ACTIVITY)" command="viewDetail"
                    >查看</el-dropdown-item
                  >
                  <el-dropdown-item v-if="$can(ButtonPermission.UPDATE_ACTIVITY)" command="edit"
                    >编辑</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-if="
                      $can(ButtonPermission.SWITCH_ACTIVITY_STATUS) &&
                      scope.row.status === ActivityStatus.OFFLINE
                    "
                    command="online"
                    >上架</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-if="
                      $can(ButtonPermission.SWITCH_ACTIVITY_STATUS) &&
                      scope.row.status === ActivityStatus.ONLINE
                    "
                    command="offline"
                    >下架</el-dropdown-item
                  >
                  <el-dropdown-item v-if="$can(ButtonPermission.DELETE_ACTIVITY)" command="delete"
                    ><span style="color: red">删除</span></el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <CommonPagination :pagination="pagination" :total="tableData.total"></CommonPagination>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="activityList">
import { reactive, ref } from 'vue';
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus';
import { readAllActivity, deleteActivity, setOnline, setOffline } from '/@/api/activity';
import { useTable } from '/@/hooks/use-table';
import CommonPagination from '/@/components/common-pagination/index.vue';
import { useRouter } from 'vue-router';
import { Activity } from '/@/models/activity';
import { ButtonPermission } from '/@/constants';
import { ActivityStatus } from '/@/constants/activity-status';
import ActivityStatusComp from '/@/components/activity-status/index.vue';
import { confirm } from '/@/utils/confirm';
import { formatDate } from '/@/utils';

const router = useRouter();

const searchFormRef = ref<FormInstance>();
const searchForm = reactive({
  name: '',
  type: undefined,
  merchant_id: undefined,
  status: undefined
});

const { tableData, loading, pagination, refresh } = useTable<Activity>(({ page, pageSize }) =>
  readAllActivity({ page, pageSize, ...searchForm }).then(({ data }) => {
    return {
      total: data?.total,
      list: data?.list
    };
  })
);

const onRest = () => {
  searchFormRef.value?.resetFields();
  refresh();
};

const handleAdd = () => {
  router.push({ name: 'activityCreate' });
};

const handleViewDetail = (row: Activity) => {
  router.push({ name: 'activityDetail', query: { id: row.id } });
};

const handleEdit = (row: Activity) => {
  router.push({ name: 'activityEdit', query: { id: row.id } });
};

const handleUploadPhoto = (row: Activity) => {
  router.push({ name: 'activityPhoto', query: { activity_id: row.id, name: row.name } });
};

const handleDistributionSettings = (row: Activity) => {
  router.push({ name: 'activityDistribution', query: { activity_id: row.id, name: row.name } });
};


const handleManageItems = (row: Activity) => {
  router.push({ name: 'activityItems', query: { activity_id: row.id, name: row.name } });
};

const handleToggleStatus = (status: string, row: any) => {
  const message = status === 'online' ? '是否确认上架' : '是否确认下架';
  confirm(
    async () => {
      if (status === 'online') {
        await setOnline(row.id);
      } else {
        await setOffline(row.id);
      }
      refresh();
    },
    message,
    '提示'
  );
};

const onCommand = (command: string, row: Activity) => {
  switch (command) {
    case 'delete':
      handleDelete(row);
      break;
    case 'edit':
      handleEdit(row);
      break;
    case 'online':
      handleToggleStatus('online', row);
      break;
    case 'offline':
      handleToggleStatus('offline', row);
      break;
    case 'viewDetail':
      handleViewDetail(row);
      break;
  }
  console.log(command, row);
};

// 删除字典
const handleDelete = (row: Activity) => {
  ElMessageBox.confirm(`此操作不可恢复，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    buttonSize: 'default',
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true;
        instance.confirmButtonText = '提交中';
        deleteActivity(row.id).then(() => {
          ElMessage.success('删除成功');
          refresh();
        });
        instance.confirmButtonLoading = false;
        done();
      } else {
        done();
      }
    }
  });
};
</script>

<style scoped lang="scss">
.system-user-container {
  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: auto;
    .el-table {
      flex: 1;
    }
  }
}
</style>
